package vn.candyapp.qlct.adapter;

import vn.candyapp.qlct.R;
import vn.candyapp.qlct.database.DBAdapter;
import vn.candyapp.qlct.database.model.Category;
import vn.candyapp.qlct.database.model.CategoryList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class CategoryAdapter extends BaseAdapter {

	private Activity _activity;
	private DBAdapter dbAdapter;
	private CategoryList mCategoriesList;
	private LayoutInflater mInflater;
	
	public CategoryAdapter(Activity activity) {
		_activity = activity;
		dbAdapter = new DBAdapter(activity);
		mInflater = LayoutInflater.from(activity);
	}
	
	public void load(final Runnable run) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				mCategoriesList = dbAdapter.getAllCategories();
				_activity.runOnUiThread(run);
			}
		}).start();
	}
	
	@Override
	public int getCount() {
		return mCategoriesList.getCategoriesList().size();
	}

	@Override
	public Object getItem(int position) {
		return mCategoriesList.getCategoryAtPosition(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.simple_list_item_2, parent, false);
			holder = new ViewHolder();
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		Category cat = (Category) getItem(position);
		holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
		holder.textView1.setText(cat.getName());
		holder.textView2 = (TextView) convertView.findViewById(R.id.textView2);
		holder.textView2.setVisibility(View.VISIBLE);
		holder.textView2.setText(cat.getTransactionType() == 2 ? "Khoản thu" : "Khoản chi");
		return convertView;
	}
	
	private class ViewHolder {
		public TextView textView1, textView2;
	}

}
